/**
 * [description]
 * @author lu.hong 2016-09-09
 * @param  {Object} $translate) {	var        graphService [description]
 * @param  {Array}  links       [description]
 * @return {[type]}             [description]
 */
angular.module('app').factory('graphService', ['$translate','serverService','ngNotify','$http','localStorageService',function($translate,serverService,ngNotify,$http,localStorageService) {
	var echarts = require('echarts');
	//var d3 = require('d3');

	var graphService = {
		//格式化返回的数据，使其成为图表支持的格式
		ResToNewJSON : function(res){
			function idIndex(a,id) {
				for (var i=0;i<a.length;i++) {
				if (a[i].id == id) return i;}
				return null;
			};
			var nodes=[], links=[];
			var categories = [];
			var linktype = [];
			var _arr1 = [] ;
			var _arr2 = [];
			var _arr3 = [];
			var _arr4 = [];
			var i = 1;
			var j = -1;
			var k = 0;
			var m = -1;
			res.results[0].data.forEach(function (row) {
				row.graph.nodes.forEach(function (n) {
					if (idIndex(nodes,n.id) == null){
						//nodes.push({id:n.id,label:n.labels[0],title:n.properties.name});
						if(!_arr1[n.labels[0]]){
							_arr1[n.labels[0]] = n.labels[0];
							j++;
							_arr2[j] = n.labels[0];
							categories[j] = {"name":n.labels[0],"num":i};
						}else{
							categories[$.inArray(n.labels[0],_arr2)].num += i;
						}
						nodes.push({id:n.id,category:$.inArray(n.labels[0],_arr2),name:n.properties.name,tagline:n.properties.tagline,title:n.properties.title});
					}
				});
				links = links.concat( row.graph.relationships.map(function(r) {
					//return {start:idIndex(nodes,r.startNode),end:idIndex(nodes,r.endNode),type:r.type};
					if(!_arr3[r.type]){
						_arr3[r.type] = r.type;
						m++;
						_arr4[m] = r.type;
						linktype[m] = {"type":r.type,"num":1};
					}else{
						linktype[$.inArray(r.type,_arr4)].num += 1;
					}
					return {source:idIndex(nodes,r.startNode),target:idIndex(nodes,r.endNode),type:r.type};
				}));
			});
			var viz = {categories:categories, nodes:nodes, links:links,linktype:linktype};
			return viz;
		},
		//生成charts的方法(echarts)
		graphInit : function(id){
			// 基于准备好的dom，初始化echarts实例
			var myChart = echarts.init(document.getElementById(id));
			myChart.showLoading();
			return myChart;
		},
		//绘制charts
		drawGraph : function(myChart,data,opts){
			myChart.hideLoading();
			defs = {
				legend: {
					show:false,
		            data: data.categories.map(function (a) {
		                return a.name;
		            })
		        },
				series: [{
					type: 'graph',
					layout: 'force',//力引导布局
					force: {
	                    //edgeLength: 100,
		                repulsion: 500
	                },
		            //animation: false,
		            symbolSize:50,//圆点大小
		            edgeSymbol: ['circle', 'arrow'],
            		edgeSymbolSize: [4, 10],
            		edgeLabel:{
            			normal :{
            				show:true
            			}
            		},
		            label: {
		                normal: {
		                	show:true ,
		                    //position: 'right',
		                    formatter: function(value){
	                    		//console.log(value);
	                    		if(value.data.name){
	                    			//此处可以根据实际需求截取字符串
	                    			return value.data.name.split(" ").join("\n");
	                    			//value.data.name
	                    		}
	                    		if(value.data.title){
	                    			return value.data.title.split(" ").join("\n");
	                    		}
	                    		if(value.data.id){
									return value.data.id
	                    		}
	                    		if(value.data.type){
									return value.data.type
	                    		}
	                    		return "";
		                    }
		                }
		            },
		            itemStyle:{
		            	normal:{
		            		borderColor : '#002948',
		            		borderWidth:1,
		            		borderType :'solid'
		            	},
		            	emphasis:{
		            		borderColor : 'rgba(0, 117, 208, 0.2)',
		            		borderWidth:10,
		            		borderType :'solid'
		            	}
		            },
		            lineStyle:{
						emphasis:{
							width :10,
							color :'rgba(0, 117, 208, 0.6)'
						}
		            },
		            roam: true,
		            draggable: true,
		            categories: data.categories,
		            data: data.nodes,
		            edges: data.links
		        }]
		    };
		    var options = $.extend({}, defs, opts);//合并对象
		    myChart.setOption(options);
		    $(window).resize(function(){
				myChart.resize();
			});
		},
		//处理后台返回的数据(graphone)
		ResToGraphJSON: function(respone,existingNodes,success) {
			var rawdata = respone;
			if(rawdata.errors.length> 0){
				success('',rawdata);
				return false;
			}
			serverService.loadSettings();
			var graphSetting = localStorageService.get('Settings');
			var _this = this;
			if(!existingNodes){
				existingNodes = [];
			}
			var displayedSize = rawdata.results[0].data.length;
			if(displayedSize > graphSetting.maxRows){
				displayedSize = graphSetting.maxRows;
			}
			var resultData = this.ResToNewJSON(rawdata);
			if(!resultData.nodes.length){
				success(resultData,rawdata);
				return false;
			}
			var newNodes = resultData.nodes;
			var newCategories = resultData.categories;
			if(resultData.nodes.length > graphSetting.initialNodeDisplay){
				newNodes = resultData.nodes.slice(0, graphSetting.initialNodeDisplay);
			}
			var mapIds = function(node){
				var reg = /^[0-9]+$/;
				if(!reg.test(node.id)){
					return node.id;
				}else{
					return parseInt(node.id);
				}
			}
			var newNodeIds = newNodes.map(mapIds);
			var existingNodeIds = existingNodes.map(mapIds).concat(newNodeIds);

			var data = {
				"statements":[{
					"statement":"MATCH (a)-[r]->(b) WHERE id(a) IN {node_ids}\nAND id(b) IN {new_node_ids}\nRETURN r;",
					"parameters":{
						"node_ids":existingNodeIds,
						"new_node_ids":newNodeIds
					},
					"resultDataContents":["row","graph"],
					"includeStats":true
				}]
			};
			serverService.sendPost(serverService.commitUrl , data , function(_res){
				//console.log(_res);
				if(!_res.results[0].data.length){
					success(resultData,rawdata);
				}else{
					var data = _this.ResToNewJSON(_res);
					/**
					$.each(newCategories,function(index,category){
						category.num = 0;
					});
					$.each(newNodes,function(index,node){
						var category = node.category;//所属类别
						newCategories[category].num += 1;
					});
					***/
					var drawdata = {
						categories:data.categories, 
						nodes:newNodes, 
						links:data.links,
						linktype:data.linktype
					};
					success(drawdata,rawdata);
				}
			});
	    }
	    //internalRelationships End
	    //graphService End
	}

	return graphService;
}]);